package com.lzh.mybatisdemo.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.TypeException;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description: json对象
 * @Author: LiuZiHao
 * @Date: 2022/4/29 11:12
 */
public class JsonObjectTypeHandler extends BaseTypeHandler<Object> {

    private static final String TYPE_NAME_VARCHAR = "varchar";

    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        String typeName = TYPE_NAME_VARCHAR;
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String s = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parameter);

        if (typeName == null) {
            throw new TypeException("ArrayTypeHandler parameter typeName error, your type is " + parameter.getClass().getName());
        }
        ps.setString(i, s);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonNodeStr = rs.getString(columnName);
        JsonNode jsonNode=null;
        if (StringUtils.hasText(jsonNodeStr)){
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                jsonNode = objectMapper.readValue(jsonNodeStr, JsonNode.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonNode;
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
